<template>
  <div class="app-container">
    <div v-if="isShowSearchBtn" class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item prop="title" label="关键字">
          <el-input
            v-model="queryParams.title"
            placeholder="请输入消息主题"
            clearable
            style="width: 350px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="resetQuery"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <div class="flex justify-between">
          <div>
            <el-button
              v-hasPerm="['message@add']"
              type="success"
              @click="openDrawer()"
              ><i-ep-plus />新增</el-button
            >
            <el-button
              v-hasPerm="['message@del']"
              type="danger"
              v-if="removeIds.length > 0"
              @click="handleDelete()"
              ><i-ep-delete />删除</el-button
            >
          </div>
          <div>
            <el-button
              class="ml-3"
              @click="handleSearchShowBtn"
              icon="Search"
              circle
            />
            <el-button
              class="ml-3"
              title="刷新"
              @click="handleQuery"
              icon="Refresh"
              circle
            />
          </div>
        </div>
      </template>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="MessageList"
        @selection-change="handleSelectionChange"
        @sort-change="handleSortChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          key="id"
          label="ID"
          align="center"
          prop="id"
          width="100"
          sortable="custom"
        />
        <el-table-column label="主题" prop="title" />
        <el-table-column label="正文" prop="content" />
        <el-table-column label="发送时间" prop="created_at" width="200" />"
        <el-table-column fixed="right" label="操作" width="220">
          <template #default="scope">
            <el-button
              v-hasPerm="['message@index']"
              type="success"
              circle
              @click="openDrawer()"
              title="查看"
            >
              <i-ep-message />
            </el-button>
            <el-button
              v-hasPerm="['message@del']"
              type="danger"
              circle
              title="删除"
              @click="handleDelete(scope.row.id)"
            >
              <i-ep-delete />
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.p"
        v-model:limit="queryParams.limit"
        @pagination="handleQuery"
      />
    </el-card>
    <!-- 角色表单弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      title="用户选择"
      width="65%"
      @close="closeDialog"
    >
      <el-row :gutter="20" style="padding: 25px">
        <el-col :span="6">
          <el-card shadow="never" class="table-container">
            <el-tree
              :data="orgTreeData"
              :props="defaultProps"
              :default-expand-all="true"
              @node-click="handleOrg"
            />
          </el-card>
        </el-col>
        <el-col :span="10">
          <el-card shadow="never" class="table-container">
            <template #header>
              <div class="flex justify-between">
                <div style="display: inline-block">
                  <el-form
                    ref="queryUserFormRef"
                    :model="queryUserParams"
                    :inline="true"
                    style="margin-bottom: -16px"
                  >
                    <el-form-item prop="title" style="margin-right: 5px">
                      <el-input
                        v-model="queryUserParams.title"
                        placeholder="请输入用户名"
                        clearable
                        style="width: 150px"
                        @keyup.enter="handleUserQuery"
                      />
                    </el-form-item>
                    <el-form-item style="margin-right: 0">
                      <el-button type="primary" @click="handleUserQuery"
                        ><i-ep-search />搜索</el-button
                      >
                      <el-button @click="resetUserQuery">
                        <i-ep-refresh />
                        重置</el-button
                      >
                    </el-form-item>
                  </el-form>
                </div>
              </div>
            </template>
            <el-table :data="userList">
              <el-table-column width="45px">
                <template #default="scope">
                  <el-button
                    icon="Plus"
                    circle
                    @click="addUser(scope.row, 'add')"
                  />
                </template>
              </el-table-column>
              <el-table-column property="avatar" label="头像" width="65px">
                <template #default="scope">
                  <el-avatar
                    :src="scope.row.avatar"
                    :size="32"
                    class="role-avatar"
                  />
                </template>
              </el-table-column>
              <el-table-column property="nickname" label="用户名" />
              <el-table-column property="username" label="账号" />
            </el-table>
            <pagination
              v-if="totalUser > 0"
              v-model:total="totalUser"
              v-model:page="queryUserParams.p"
              v-model:limit="queryUserParams.limit"
              @pagination="handleUserQuery"
            />
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card shadow="never" class="table-container">
            <template #header>
              <div class="flex justify-between">
                <span class="role-avatar">已选择：{{ checkUserNumber }}</span>
                <el-button
                  type="danger"
                  @click="addUser([], 'remove', true)"
                  circle
                  aria-label="移除"
                  ><i-ep-minus
                /></el-button>
              </div>
            </template>
            <el-table :data="checkUserLst">
              <el-table-column width="45px">
                <template #default="scope">
                  <el-button
                    type="danger"
                    icon="Minus"
                    circle
                    @click="addUser(scope.row, 'remove')"
                  />
                </template>
              </el-table-column>
              <el-table-column property="avatar" label="头像" width="65px">
                <template #default="scope">
                  <el-avatar
                    :src="scope.row.avatar"
                    :size="32"
                    class="role-avatar"
                  />
                </template>
              </el-table-column>
              <el-table-column property="nickname" label="用户名" />
            </el-table>
          </el-card>
        </el-col>
      </el-row>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="closeDialog">取消</el-button>
          <el-button type="primary" @click="confirmAuthUser">确认</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 发送消息 -->
    <el-drawer v-model="drawer" title="发送消息" direction="rtl" size="65%">
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="消息主题" prop="title">
          <el-input v-model="formData.title" placeholder="请输入消息主题" />
        </el-form-item>

        <el-form-item label="正文" prop="content">
          <el-input
            type="textarea"
            v-model="formData.content"
            rows="6"
            placeholder="请输入正文"
          />
        </el-form-item>
        <el-form-item label="接受人" prop="user_id">
          <div
            class="message-avatar"
            v-for="item in checkUserLst"
            :key="item.id"
          >
            <el-avatar
              :src="item.avatar"
              :size="32"
              class="role-avatar"
              style="margin: 0 12px"
            />
            <el-icon
              class="remove-user"
              @click="addUser(item, 'remove')"
              size="16"
              ><Close
            /></el-icon>
          </div>
          <el-icon
            @click="openDialog()"
            size="32"
            style="cursor: pointer; margin-left: 5px"
            ><CirclePlus
          /></el-icon>
        </el-form-item>
      </el-form>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="drawer = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确认</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { addMessage, deleteMessages, getMessagePage } from "@/api/message";
import { MessageForm, MessagePageVO, MessageQuery } from "@/api/message/types";
import { getUserPage } from "@/api/role";
import { orgTree } from "@/api/organization";
import { UserQuery, UserPageVO } from "@/api/user/types";

defineOptions({
  name: "Role",
  inheritAttrs: false,
});

const queryFormRef = ref(ElForm);
const queryUserFormRef = ref(ElForm);
const formRef = ref(ElForm);
const loading = ref(false);
const total = ref(0);
const totalUser = ref(0);
const isShowSearchBtn = ref(false);
const isEdit = ref(true);
const drawer = ref(false);
const removeIds = ref([]); // 删除ID集合 用于批量删除
const selectedRows = ref([]);
const queryParams = reactive<MessageQuery>({
  p: 1,
  limit: 10,
});
const queryUserParams = reactive<UserQuery>({
  p: 1,
  limit: 10,
});
const MessageList = ref<MessagePageVO[]>();
const userList = ref<UserPageVO[]>();
const checkUserLst = ref<UserPageVO[]>();
const checkUserIds: Ref<number[]> = ref([]);
const checkUserNumber = ref(0);
const dialog = reactive({
  title: "",
  visible: false,
});
const formData = reactive<MessageForm>({
  id: undefined,
  sort: 0,
});
const rules = reactive({
  title: [{ required: true, message: "请输入消息主题", trigger: "blur" }],
  content: [{ required: true, message: "请输入正文", trigger: "blur" }],
  user_id: [{ required: true, message: "请选择接受人", trigger: "blur" }],
});
const orgTreeData = ref<OptionType[]>(); //组织架构下拉数据源
const defaultProps = ref({
  children: "children",
  label: "title",
});
/** 组织架构树 */
function orgQuery() {
  orgTree()
    .then(({ data }) => {
      orgTreeData.value = data;
      const options: OptionType = orgTreeData.value[0];
      queryUserParams.id =
        typeof options.value === "string"
          ? parseInt(options.value)
          : options.value;
      getUserPage(queryUserParams)
        .then(({ data }) => {
          userList.value = data.items;
          totalUser.value = data.total;
        })
        .finally(() => {});
    })
    .finally(() => {});
}

function addUser(user?: UserPageVO, type?: string, isAll?: boolean) {
  if (user != undefined) {
    if (type === "add") {
      if (checkUserLst.value != undefined) {
        checkUserLst.value.push(user);
      }
      if (user.id != undefined) {
        checkUserIds.value.push(user.id);
      }
      if (userList.value != undefined) {
        userList.value = userList.value.filter((item) => {
          return item.id !== user.id;
        });
      }
    } else {
      if (isAll === true) {
        checkUserIds.value = [];
        if (userList.value != undefined && checkUserLst.value != undefined) {
          const mergedArray: UserPageVO[] = [
            ...userList.value,
            ...checkUserLst.value,
          ];
          userList.value = [
            ...new Map(mergedArray.map((item) => [item.id, item])).values(),
          ];
          checkUserLst.value = [];
        }
      } else {
        if (checkUserLst.value != undefined) {
          checkUserLst.value = checkUserLst.value.filter((item) => {
            return item.id !== user.id;
          });
        }
        if (checkUserIds.value != undefined) {
          checkUserIds.value = checkUserIds.value.filter((item) => {
            return item !== user.id;
          });
        }
        if (userList.value != undefined) {
          //先移除后添加
          userList.value = userList.value.filter((item) => {
            return item.id !== user.id;
          });
        }
        if (userList.value != undefined) {
          userList.value?.push(user);
        }
      }
    }
    checkUserNumber.value =
      checkUserLst.value != undefined ? checkUserLst.value.length : 0;
  }
}

/**
 * 确认选择
 */
function confirmAuthUser() {
  formData.user_id = checkUserIds.value;
  closeDialog();
}

/**
 * 查询组织架构树下的用户
 * @param tree
 */
function handleOrg(tree: any) {
  queryUserParams.id = tree.id;
  getUserPage(queryUserParams)
    .then(({ data }) => {
      userList.value = data.items;
    })
    .finally(() => {});
}
function handleUserQuery() {
  getUserPage(queryUserParams)
    .then(({ data }) => {
      userList.value = data.items;
    })
    .finally(() => {});
}
/** 查询 */
function handleQuery() {
  loading.value = true;
  getMessagePage(queryParams)
    .then(({ data }) => {
      MessageList.value = data.items;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}
/** 重置查询 */
function resetQuery() {
  queryFormRef.value.resetFields();
  queryParams.p = 1;
  handleQuery();
}

function resetUserQuery() {
  queryUserFormRef.value.resetFields();
  queryUserParams.p = 1;
  handleUserQuery();
}

function openDrawer() {
  userList.value = [];
  checkUserLst.value = [];
  checkUserIds.value = [];
  checkUserNumber.value = 0;
  drawer.value = drawer.value == false;
}

/** 打开表单弹窗 */
function openDialog() {
  dialog.visible = true;
  orgQuery();
}

/** 保存提交 */
function handleSubmit() {
  formRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      addMessage(formData)
        .then(() => {
          resetForm();
          drawer.value = false;
          handleQuery();
          ElMessage.success("发送成功");
        })
        .finally(() => (loading.value = false));
    }
  });
}

/** 关闭表单弹窗 */
function closeDialog() {
  dialog.visible = false;
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  selectedRows.value = [];
  formData.id = undefined;
  formData.user_id = [];
  formData.title = "";
  formData.content = "";
  handleQuery();
}

/** 删除 */
function handleDelete(id?: number) {
  const ids = id || removeIds.value;
  if (!ids) {
    ElMessage.warning("请勾选删除项");
    return;
  }
  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    loading.value = true;
    deleteMessages({ ids: ids })
      .then(() => {
        ElMessage.success("删除成功");
        handleQuery();
      })
      .finally(() => (loading.value = false));
  });
}

/** 行选中 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

//收起展开搜索按钮
function handleSearchShowBtn() {
  isShowSearchBtn.value = isShowSearchBtn.value === false;
}

/** 排序 */
function handleSortChange(data: any) {
  const { prop, order } = data;
  if (prop === "id") {
    if (order === "ascending") {
      queryParams.sort = "+id";
    } else {
      queryParams.sort = "-id";
    }
    handleQuery();
  }
}

onMounted(() => {
  handleQuery();
});
</script>

<style>
.message-avatar {
  display: inline-block;
  position: relative;
}
.message-avatar .remove-user {
  position: absolute;
  right: 0;
  top: -10px;
  color: var(--el-color-danger);
  cursor: pointer;
}
.role-avatar {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
